import { boot } from 'quasar/wrappers';
import axios, { AxiosInstance } from 'axios';
import { useCommonStore } from 'stores/commonStore';
import { storeToRefs } from 'pinia';

declare module '@vue/runtime-core' {
  interface ComponentCustomProperties {
    $axios: AxiosInstance;
  }
}

// Be careful when using SSR for cross-request state pollution
// due to creating a Singleton instance here;
// If any client changes this (global) instance, it might be a
// good idea to move this instance creation inside of the
// "export default () => {}" function below (which runs individually
// for each client)
const api = axios.create({ baseURL: 'https://api.example.com' });

export default boot(({ app, router }) => {
  // for use inside Vue files (Options API) through this.$axios and this.$api

  app.config.globalProperties.$axios = axios;
  // ^ ^ ^ this will allow you to use this.$axios (for Vue Options API form)
  //       so you won't necessarily have to import axios in each vue file

  app.config.globalProperties.$api = api
  // ^ ^ ^ this will allow you to use this.$api (for Vue Options API form)
  //       so you can easily perform requests against your app's API

  //请求拦截器
  axios.interceptors.request.use((config) => {
    //登录页面不需要增加token
    if (config.url !== '/auth/login') {
      //commStore
      let commonStore = useCommonStore();
      const {
        token
      } = storeToRefs(commonStore);
      debugger
      //console.log(token);
      if ((token.value) && (token.value !== '')) {
        config.headers.Authorization = token.value;
      }
    }
    return config;
  }, (error) => {
    //alert('请求超时');
    return Promise.reject(error);
  });

  //响应拦截器
  axios.interceptors.response.use((response) => {
    if (response.data.code === 200) {
      // 请求成功对响应数据做处理
      // 该返回的数据则是axios.then(res)中接收的数据
      return response;
    } else {
      //没有通过验证,response.data.code = 401;
      let msg = 'axios is error!'
      console.log(msg);

      //token清空
      let commonStore = useCommonStore();
      commonStore.initToken();

      //替换路由
      router.replace('/auth/login');

      //返回无效
      return response;
    }
  }, (error) => {
    // 在请求错误时要做的事儿
    let commonStore = useCommonStore();
    commonStore.initToken();

    // 该返回的数据则是axios.catch(err)中接收的数据
    return Promise.reject(error);
  });
});

export { api };
